package cn.good.yan.controller.t1;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonMultiLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * 演示 - Redis
 *     3台Redis主机的分布式锁
 *
 * @author shengren.yan
 * @create 2023-11-08
 */
@RestController
@RequestMapping("/t1")
@Slf4j
@Api(tags = "订单接口")
public class OrderController {

    // 分布式集群锁的总key
    public static final String CACHE_KEY_REDLOCK = "ATGUIGU_REDLOCK";

    @Autowired
    RedissonClient redissonClient1;

    @Autowired
    RedissonClient redissonClient2;

    @Autowired
    RedissonClient redissonClient3;

    boolean isLockBoolean;

    @ApiOperation("3台Redis主机的分布式锁")
    @GetMapping(value = "/multiLock")
    public String getMultiLock() throws InterruptedException {
        String uuid = UUID.randomUUID().toString();
        String uuidValue = uuid + ":" + Thread.currentThread().getId();

        RLock lock1 = redissonClient1.getLock(CACHE_KEY_REDLOCK);
        RLock lock2 = redissonClient2.getLock(CACHE_KEY_REDLOCK);
        RLock lock3 = redissonClient3.getLock(CACHE_KEY_REDLOCK);

        RedissonMultiLock redLock = new RedissonMultiLock(lock1, lock2, lock3);
        // 加锁
        redLock.lock();
        try {
            System.out.println(uuidValue + "\t" + "---come in biz multiLock");
            try {
                TimeUnit.SECONDS.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(uuidValue + "\t" + "---task is over multiLock");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("multiLock exception ", e);
        } finally {
            // 解锁
            redLock.unlock();
            log.info("释放分布式锁成功key:{}", CACHE_KEY_REDLOCK);
        }
        return "multiLock task is over  " + uuidValue;
    }

}
